<!DOCTYPE html>
<html lang="zh_CN">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="./css/bootstrap/bootstrap.min.css" />

    <title>动态表格</title>
  </head>
  <body>
    <div id="app">
      <div class="container mt-5">
        <div class="row justify-content-center mb-2">
          <div class="col-6 ml-5">
            <input
              type="text"
              placeholder="员工编号"
              v-model="id"
              v-focus
              :disabled="flag"
            />
            <input type="text" placeholder="员工姓名" v-model="name" />
            <input type="button" @click="addHandle" :disabled='btnFlag' value="添加" />
          </div>
        </div>
        
        <div class="row justify-content-center">
          <div class="col-6">
            <table class="table table-striped table-bordered text-center">
              <tr>
                <th>编号</th>
                <th>姓名</th>
                <th>入职时间</th>
                <th>操作</th>
              </tr>
              <tr :key="emp.id" v-for="emp in emps">
                <td>{{emp.id}}</td>
                <td>{{emp.name}}</td>
                <td>{{emp.hireDate | format('yyyy-MM-dd')}}</td>
                <td>
                  <a href="" @click.prevent="deleteHandle(emp.id)">删除</a>
                  <span>|</span>
                  <a href="" @click.prevent="editHandle(emp.id)">修改</a>
                </td>
              </tr>
            </table>
          </div>
        </div>
        <div class="row justify-content-center mb-2">
          <div class="col-6 ml-5 text-center ">
             <h5>员工总数为:{{total}}</h5>
          </div>
        </div>
      </div>
    </div>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="js/jQuery/jquery-3.4.1.slim.min.js"></script>
    <script src="js/bootstrap/popper.min.js"></script>
    <script src="js/bootstrap/bootstrap.min.js"></script>
    <script src="js/vue.js"></script>
    <script>
       /*自定义指令:获得焦点*/
       Vue.directive('focus',{
         inserted:function(el){
           el.focus();
         }
       });

       /*定义过滤器:处理日期格式*/
       Vue.filter('format',function(value,pattern){
				function dateFormat(date, format) {
				    if (typeof date === "string") {
				        var mts = date.match(/(\/Date\((\d+)\)\/)/);
				        if (mts && mts.length >= 3) {
				            date = parseInt(mts[2]);
				        }
				    }
				    date = new Date(date);
				    if (!date || date.toUTCString() == "Invalid Date") {
				        return "";
				    }
				    var map = {
				        "M": date.getMonth() + 1, //月份 
				        "d": date.getDate(), //日 
				        "h": date.getHours(), //小时 
				        "m": date.getMinutes(), //分 
				        "s": date.getSeconds(), //秒 
				        "q": Math.floor((date.getMonth() + 3) / 3), //季度 
				        "S": date.getMilliseconds() //毫秒 
				    };
				
				    format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
				        var v = map[t];
				        if (v !== undefined) {
				            if (all.length > 1) {
				                v = '0' + v;
				                v = v.substr(v.length - 2);
				            }
				            return v;
				        } else if (t === 'y') {
				            return (date.getFullYear() + '').substr(4 - all.length);
				        }
				        return all;
				    });
				    return format;
				}
				return  dateFormat(value,pattern);
			});

      const vm = new Vue({
        el: "#app",
        data: {
          flag: false,
          btnFlag:false,
          id: "",
          name: "",
          emps: [],
        },
        computed:{
          total:function(){
            return this.emps.length;
          }
        },
        methods: {
          addHandle() {
            if (this.flag) {
              //表示为修改数据
              //1. 根据当前的id更新集合中的数据
              this.emps.some((item) => {
                if (item.id == this.id) {
                  item.name = this.name;
                  //完成更新之后,终止循环
                  return true;
                }
              });
              this.flag = false;
            } else {
              //添加数据
              let emp = {};
              emp.id = this.id;
              emp.name = this.name;
              emp.hireDate = new Date();
              //将emp添加到emps中
              this.emps.push(emp);
            }
            //清除输入框中的内容
            this.id = "";
            this.name = "";
          },
          editHandle(id) {
            console.log(id);
            //将id的文本框设置为不可编辑
            this.flag = true;
            //1. 根据id从emps中获得对应的数据
            let emp = this.emps.filter((obj) => obj.id == id);
            console.log(emp);
            this.id = emp[0].id;
            this.name = emp[0].name;
          },
          deleteHandle(id) {
            //方法1:
            //1.根据id值获得数组中对应的数据
            //let index=this.emps.findIndex(item=> item.id==id);
            //2.根据下标删除数组元素
            // this.emps.splice(index,1);
            //方法2: 采用filter
            this.emps=this.emps.filter( item=> item.id!=id);
          },
        },
        watch:{
          name(val){
             //验证员工的姓名是否已经存在
            let flag = this.emps.some(item=> item.name==val);
            this.btnFlag=flag;
            
          }
        },
        mounted:function(){
          //生命周期钩子函数,虚拟DOm已经挂载完毕.可以通过该函数从后台获取数据
         let datas=[
            {
              id: 1001,
              name: "haoren",
              hireDate: 1576778461000
            },
            {
              id: 1002,
              name: "lucy",
              hireDate:1576778461000
            },
            {
              id: 1003,
              name: "lily",
              hireDate: 1576778461000
            },
            {
              id: 1004,
              name: "jerry",
              hireDate:1576778461000
            },
            {
              id: 1005,
              name: "batman",
              hireDate: 1576778461000
            },
          ];
          this.emps=datas;
        }

      });
    </script>
  </body>
</html>
